# -*- coding:utf-8 -*-

import os
import sys
import time
import smtplib
import traceback
from ConfigParser import ConfigParser as Parser
from email.header import Header
from email.mime.text import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders
from email.mime.multipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.utils import COMMASPACE, formatdate


class MailSender():
    def __init__(self, mailConfigFile):
        self.config = Parser()
        self.config.read(mailConfigFile)
        self._mailRecipients = []
        self._mailLog = self.config.get("mail","log")
        
        self._host = self.config.get("mail","host")
        self._user = self.config.get("mail","user")
        self._pwd  = self.config.get("mail","pwd")
        # 126.com as backup sender
        # self._126_host = self.config.get("126.com","host")
        # self._126_user = self.config.get("126.com","user")
        # self._126_pwd  = self.config.get("126.com","pwd")        

    def _time(self):
        return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))

    def _log(self, results):
        log = None
        if os.path.exists(self._mailLog):
            log = open(self._mailLog, 'a')
        else:
            log = open(self._mailLog, 'w')
        details = "%s\n%s\n%s\n\n" % (self._time(), results, ','.join(self._mailRecipients))
        log.write(details)
        log.close()

    def _init_recipients(self, project_name):
        recps_str = self.config.get(project_name.upper(), 'recipients').strip()
        # 去掉空格, 添加默认域名:
        for recp in recps_str.split(","):
            recp = recp.strip()
            if '@' in recp:
                self._mailRecipients.append(recp)
            else:
                self._mailRecipients.append(recp + '@unisound.com')
        print self._mailRecipients

    def _send_mail(self, title, body, attachments=None):
        mailMessage = MIMEMultipart()
        mailMessage['Subject'] = Header(title,"UTF-8")
        mailMessage['From']    = "<%s>" % self._user
        mailMessage['To']      = ','.join(self._mailRecipients)
        mailMessage['Date']    = formatdate(localtime=True)
        messageTxt = MIMEText(body,'plain', _charset='UTF-8')
        mailMessage.attach(messageTxt)

        # add attachments [附件为文件名列表]
        if attachments is not None:
            for attach_file in attachments:
                if not os.path.exists(attach_file):
                    continue
                part = MIMEBase('application', 'octet-stream')
                # 读入文件内容并格式化 
                part.set_payload(open(attach_file,'rb').read())
                Encoders.encode_base64(part)
                name = os.path.split(attach_file)[-1]
                part.add_header('Content-Disposition', 'attachment; filename="%s"' % name)
                mailMessage.attach(part)
                print "%s attached" % attach_file
        try:
            smtp = smtplib.SMTP()
            smtp.connect(self._host)
            smtp.esmtp_features["auth"]="LOGIN"
            smtp.ehlo()
            smtp.starttls()
            smtp.login(self._user, self._pwd)
            time.sleep(0.4)
            smtp.sendmail(self._user, self._mailRecipients, mailMessage.as_string())
            smtp.close()
            print 'send Mail ok'
            results = "邮件发送成功!\nTitle: %s\nMessage: %s" % (title, body)
            self._log(results)
        except Exception:
            print 'send Mail fail'
            exceptionString  = traceback.format_exc()
            results = "邮件发送失败!\nTitle: %s\nMessage: %s" % (title, body)
            results += "\n" + exceptionString.strip()
            self._log(results)

    def _send_no_reply_mail(self, title, body, attachments=None):
        mail_host = "42.159.161.202:25"
        mail_user = "no-reply@unisound.com"
        sender = "no-reply" + '<' + mail_user +  '>'

        receivers = ','.join(self._mailRecipients)
        msg = MIMEMultipart('alternative')
        msg['Subject'] = title
        msg['From'] = sender
        msg['To'] = receivers
        msg.attach(MIMEText(body, 'plain', 'utf8'))

        if attachments is not None:
            for attach_file in attachments:
                part = MIMEBase('application', 'octet-stream')
                # 读入文件内容并格式化
                part.set_payload(open(attach_file,'rb').read())
                Encoders.encode_base64(part)
                # 设置附件头
                name = os.path.split(attach_file)[-1]
                part.add_header('Content-Disposition', 'attachment; filename="%s"' % name)
                msg.attach(part)
                print "%s attached" % attach_file
        try:
            s = smtplib.SMTP()
            s.connect(mail_host)
            s.sendmail(sender, receivers, msg.as_string())
            s.close()
            print 'send Mail ok'
            results = "邮件发送成功!\nTitle: %s\nMessage: %s" % (title, body)
            self._log(results)
        except Exception:
            print 'send Mail fail'
            exceptionString  = traceback.format_exc()
            results = "邮件发送失败!\nTitle: %s\nMessage: %s" % (title, body)
            results += "\n" + exceptionString.strip()
            self._log(results)

    def _send_126_mail(self, title, body, attachments=None):
        mailMessage = MIMEMultipart()
        mailMessage['Subject'] = Header(title,"UTF-8")
        mailMessage['From']    = "<" + self._user + ">"
        mailMessage['To']      = ','.join(self._mailRecipients)
        mailMessage['Date']    = formatdate(localtime=True)
        messageTxt = MIMEText(body,'plain', _charset='UTF-8')
        mailMessage.attach(messageTxt)

        # add attachments [附件为文件名列表]
        if attachments is not None:
            for attach_file in attachments:
                if not os.path.exists(attach_file):
                    continue
                part = MIMEBase('application', 'octet-stream')
                # 读入文件内容并格式化 
                part.set_payload(open(attach_file,'rb').read())
                Encoders.encode_base64(part)
                name = os.path.split(attach_file)[-1]
                part.add_header('Content-Disposition', 'attachment; filename="%s"' % name)
                mailMessage.attach(part)
                print "%s attached" % attach_file
        try:
            print '>%s<' % self._126_host
            print '>%s<' % self._126_user
            print '>%s<' % self._126_pwd
            smtp = smtplib.SMTP()
            smtp.connect(self._126_host)
            smtp.login(self._126_user,self._126_pwd)
            smtp.sendmail(self._user, self._mailRecipients, mailMessage.as_string())
            smtp.close()
            print 'send 126.com Mail ok'
            results = "邮件发送成功!\nTitle: %s\nMessage: %s" % (title, body)
            self._log(results)
        except Exception:
            exceptionString  = traceback.format_exc()
            results = "邮件发送失败!\nTitle: %s\nMessage: %s" % (title, body)
            results += "\n" + exceptionString.strip()
            self._log(results)
            print results


    def send_mail(self, title, body, attachments=None):
        # 默认是NLU回归的收件人.
        self._init_recipients('NLU')
        self._send_no_reply_mail(title, body, attachments)

    def send_monitor_result(self, title, body, project_name, attachments=None):
        # sanity: 根据项目确定收件人
        self._init_recipients(project_name)
        # self._send_no_reply_mail(title, body, attachments)
        self._send_mail(title, body, attachments)


if __name__ == '__main__':
    title = "debug_mail_邮件调试_忽略"
    body = "See attachments for details"
    files = ['mailSender.py']
    sender = MailSender('tmp_mail.conf')
    sender.send_monitor_result(title, body, 'debug', attachments=files)